const BaseController = require('./base_controller.js');
const OrderManagementService = require('../service/order_management_service.js');

class OrderManagementController extends BaseController {

  /**
   * 获取订单列表
   */
  async getOrderList() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      page: 'int|min:1|default=1|name=页码',
      size: 'int|min:1|max:50|default=20|name=每页数量',
      status: 'int|name=订单状态',
      storeId: 'string|name=门店ID',
      userId: 'string|name=用户ID',
      dateRange: 'string|name=日期范围',
      search: 'string|max:50|name=搜索关键词',
    };

    let input = this.validateData(rules);

    try {
      const service = new OrderManagementService();
      const result = await service.getOrderList(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 取消订单
   */
  async cancelOrder() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      orderId: 'required|string|name=订单ID',
      reason: 'required|string|max:200|name=取消原因',
      refundType: 'required|string|in:balance,wechat|name=退款方式',
    };

    let input = this.validateData(rules);

    try {
      const service = new OrderManagementService();
      const result = await service.cancelOrder(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 获取订单详情
   */
  async getOrderDetail() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      orderId: 'required|string|name=订单ID',
    };

    let input = this.validateData(rules);

    try {
      const service = new OrderManagementService();
      const result = await service.getOrderDetail(input.orderId);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 联系订单用户
   */
  async contactOrderUser() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      orderId: 'required|string|name=订单ID',
    };

    let input = this.validateData(rules);

    try {
      const service = new OrderManagementService();
      const result = await service.getOrderUserContact(input.orderId);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }
}

module.exports = OrderManagementController;
